<?php

/**
 * 微信公众号
 */
namespace wechat;
use think\Db;

class Wechat{

    const APP_ID = "wxa349b654d2ceb453";
    const APP_SECRET = "01141c7c13313cdf9e1fe4d5eb305e23";
    const REDIRECT_URI = "http://dingdan.hihaoge.me/baby/index.html";
    public $redis = null;

    public function __construct()
    {
        $this->redis = new \Predis\Client(\think\Config::get('redis'));
    }

    public static function getUrl(){

        $scope = "snsapi_userinfo";

        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=". self::APP_ID."&redirect_uri=". self::REDIRECT_URI ."&response_type=code&scope=". $scope ."&state=STATE#wechat_redirect";
        return $url;
    }

    public static function getAccessToken($code,$state=''){

        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.self::APP_ID.'&secret='.self::APP_SECRET.'&code='.$code.'&grant_type=authorization_code';
        $token = json_decode(file_get_contents($token_url));
        if (isset($token->errcode)) {

            $msg = '错误： '.$token->errcode . ", 错误信息： " .$token->errmsg;
            return ['code' => 0, 'msg' =>'获取token出错', 'data' => $msg];
        }
        $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.self::APP_ID.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;

        $access_token = json_decode(file_get_contents($access_token_url));
        if (isset($access_token->errcode)) {

            $msg = '错误： '.$access_token->errcode . ", 错误信息： " .$access_token->errmsg;
            return ['code' => 0, 'msg' =>'刷新token出错', 'data' => $msg ];
        }
        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';

        $user_info = json_decode(file_get_contents($user_info_url));
        if (isset($user_info->errcode)) {
            $msg = '错误： '.$user_info->errcode . ", 错误信息： " .$user_info->errmsg;
            return ['code' => 0, 'msg' =>'获取用户信息出错', 'data' => $msg ];
        }



        return ['code' => 1, 'msg' => '', 'data' => $user_info];
    }





    public function getCommonAccessToken()
    {
        // access_token 应该全局存储与更新
        // 获取数据库中的access_token
//        $token = M('accesstoken')->limit(1)->find();

        $key = "orderbabyWechatCommonAccessToken";

        $token = $this->redis->hvals($key);


        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . self::APP_ID . "&secret=" . self::APP_SECRET;
        // 微信返回的信息
        $returnData = json_decode($this->httpGet($url));
//        dump($returnData);exit;
        // 组装数据
        $resData['accessToken'] = $returnData->access_token;
        $resData['expiresIn'] = $returnData->expires_in;
        $resData['time'] = date("Y-m-d H:i", time());
        // 把数据存进数据库
//            M('accesstoken')->where(array('id' => $token['id']))->save($resData);

        $key = "loanWechatAccessToken";
        $this->redis->hmset($key,$resData);
        $res = $resData;

        return $res;
    }

    private function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    public function getJsApiTicket($accessToken)
    {
        // jsapi_ticket 应该全局存储与更新
        // 获取数据库中的jsapi_ticket
//        $ticket = M('jsticket')->limit(1)->find();
//        $key = "loanWechatTicket";
//        $ticket = $this->redis->hvals($key);


        // 如果ticket失效

        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$accessToken&&type=jsapi";
        // 微信返回的信息
        $returnData = json_decode($this->httpGet($url));
        // 组装数据
        $resData['ticket'] = $returnData->ticket;
        $resData['expiresIn'] = $returnData->expires_in;
        $resData['time'] = date("Y-m-d H:i", time());
        $resData['errcode'] = $returnData->errcode;

        // 把数据存进数据库
//            M('jsticket')->where(array('id' => $ticket['id']))->save($resData);

//            $key = "loanWechatTicket";
//            $this->redis->hmset($key,$resData);
        $res = $resData;

        return $res;
    }

    // 获取签名
    public function getSignPackage($url)
    {
//        // 获取token
        $token = $this->getCommonAccessToken();
//
//        // 获取ticket
        $ticketList = $this->getJsApiTicket($token['accessToken']);
        $ticket = $ticketList['ticket'];


        // 该URL为使用JSSDK接口的URL
        // 时间戳
        $timestamp = time();
        // 随机字符串
        $nonceStr = $this->createNoncestr();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序 j -> n -> t -> u
        $string = "jsapi_ticket=$ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array(
            "appId" => self::APP_ID,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string,
            "ticket" => $ticket,
            "token" => $token['accessToken']
        );
        // 提供数据给前端
//        return json_encode(['code' => 1, 'msg' => '','data' => $signPackage]);
        return $signPackage;


    }


    // 创建随机字符串
    private function createNoncestr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }


    /**
     *发送模板消息
     * $access_token
     * $params
     **/
    public function sendWxMsg($user_id, $goods_id)
    {
        $access_token = $this->getCommonAccessToken();

        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token['accessToken'];
        $curl = new \Curl\Curl();
        $openid = Db::name('user')->where('id', $user_id)->value('openid');
        $goods = \app\common\model\Goods::get($goods_id);
        $jsonData = json_encode([
            'touser' => $openid,
            'template_id' => 'U276XkA8DAK5RPnoxE8eCcSojNYezPxdBSgHiB1oJAs',
            'url' => 'http://dingdan.hihaoge.me/baby/html/businessinfo.html?id=' . $goods['id'],

            'data' => [
                'first' => "尊敬的用户您好",
                'keyword1' => [
                    'value' => $goods['province_text'] . ' ' . $goods['city_text'],
                    'color' => '#173177'
                ],
                'keyword2' => [
                    'value' => $goods['updatetime'],
                    'color' => '#173177'
                ],
                'keyword3' => [
                    'value' => $goods['title'],
                    'color' => '#173177'
                ],
                'keyword4' => [
                    'value' => $goods['buy_num'],
                    'color' => '#173177'
                ]
            ]

        ]);

        $curl->post($url, $jsonData);
        $result = $curl->response;
        echo json_encode($result);

    }




}